//
//  WLUserAccountViewModel.swift
//  weibo
//
//  Created by 刁 海瑞 on 16/8/11.
//  Copyright © 2016年 毋磊. All rights reserved.
//

import UIKit

class WLUserAccountViewModel: NSObject {
    static let sharedUserAccount: WLUserAccountViewModel = WLUserAccountViewModel()
//    用户账户模型
    var userAccout: WLUserAccount? {
        return WLUserAccount.loadUserAccount()
    }
//    判断是否登录
    var isLogin: Bool {
        return accessToke != nil
    }
    var accessToke: String?{
        
        guard let token = userAccout?.access_token else {
            return nil
        }
        //  如果accesstoken不为nil,判断accesstoken的时间是否过期
        let result = userAccout?.expiresDate?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending{
            
            return token
        }else{
            
            return nil
        }
    }
    
    //    通过code获取accesstoken
    func reqeustAccessTokenWithCode(code: String, callBack: (isSuccess: Bool)->()) {
        
        WLNetworkTools.sharedTools.reqeustAccessTokenWithCode(code) { (response, error) -> () in
            if error != nil {
                print("网络请求失败\(error)")
                callBack(isSuccess: false)
                return
            }
            
            //            代码执行到此网络请求成功
            guard let dic = response as? [String: AnyObject] else{
                print("不是一个正确的字典")
                callBack(isSuccess: false)
                return
            }
            
            let userAccount = WLUserAccount(dic: dic)
            self.requestUserInfo(userAccount, callBack: callBack)
        }
    }
    
    //   通过accesstoken和uid获取用户信息
     func requestUserInfo(userAccount: WLUserAccount, callBack: (isSuccess: Bool)->()){
        
        WLNetworkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
            
            if error != nil {
                
                print("网络加载失败")
                callBack(isSuccess: false)
                return
            }
            //            代码执行到此网络请求成功
            guard let dic = response as? [String: AnyObject] else{
                print("不是一个正确的字典")
                callBack(isSuccess: false)
                return
            }
            
            let name = dic["name"]
            let avatar_large = dic["avatar_large"]
            
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            
            //            表示用户登录成功
            //            保存用户账号的模型
            userAccount.saveUserAccount()
            callBack(isSuccess: true)
            
        }
        
   
    }

    
}
